var api = require('../config/api.js');

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 封装微信的的request
 */
function request(url, data = {}, method = "GET") {
  let _this = this
  var token = wx.getStorageSync('token')
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'X-Nideshop-Token': token
      },
      success: function (res) {
        // console.log("success");


        if (res.statusCode == 200) {

          if (res.data.errno == 401) {
            let pages = getCurrentPages();
            let currPage = null;
            if (pages.length) {
              currPage = pages[pages.length - 1];
            }
            //需要登录后才可以操作
            //(登录页不需要提醒)
            if(currPage.__route__ !== 'pages/me/me'){
              console.log(currPage.__route__)
              wx.showModal({
                title: '',
                content: '请先登录',
                showCancel:false,
                success: function (res) {
                  if (res.confirm) {
                    wx.removeStorageSync("userInfo");
                    wx.removeStorageSync("token");

                    wx.switchTab({
                      url: '/pages/me/me'
                    });
                  }
                }
              });
            }
          } else {
            resolve(res.data);
          }
        } else {
          reject(res.errMsg);
        }

      },
      fail: err=> {
        reject(err)
        _this.showErrorToast('请求超时')
      }
    })
  });
}


function post(url, data) {
  var token = wx.getStorageSync('token')
  return new Promise(function (resolve, reject) {
    wx.request({
      url:url,
      data: data,
      header: {
        'content-type': 'application/json',
        'X-Nideshop-Token': token
      },
      method: "POST",
      success: function (res) {
        // console.log("success");


        if (res.statusCode == 200) {

          if (res.data.errno == 401) {
            //需要登录后才可以操作
            wx.showModal({
              title: '',
              content: '请先登录',
              success: function (res) {
                if (res.confirm) {
                  wx.removeStorageSync("userInfo");
                  wx.removeStorageSync("token");

                  wx.switchTab({
                    url: '/pages/me/me'
                  });
                }
              }
            });
          } else {
            resolve(res.data);
          }
        } else {
          reject(res.errMsg);
        }

      },
      fail: err=> {
        if (err.errMsg === "request:fail timeout") {
          _this.showErrorToast('请求超时')
        } else {
          reject(err)
        }  
      }
    })
  })


}


//封装wx.showModel为alert
function alert(msg = '',confirm,cancel) {
  wx.showModal({
    title: '提示',
    content: msg,
    showCancel: cancel ? true : false,
    success:res=>{
      if(res.confirm){
        if(confirm){
          confirm()
        }
      }
      if(res.cancel){
        if(cancel){
          cancel()
        }
      }
    }
  })
}

//计算两地距离
function getDistance(lat1, lng1, lat2, lng2) {
  lat1 = lat1 || 0;
  lng1 = lng1 || 0;
  lat2 = lat2 || 0;
  lng2 = lng2 || 0;

  var rad1 = lat1 * Math.PI / 180.0;
  var rad2 = lat2 * Math.PI / 180.0;
  var a = rad1 - rad2;
  var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
  var r = 6378137;
  var distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));
  if(distance > 1000){
    distance = Math.round(distance / 1000)
  }else{
    distance = (distance/1000).toFixed(2)
  }
  // console.log('距离', distance)
  return distance;
}





/**
 * 检查微信会话是否过期
 */
function checkSession() {
  return new Promise(function (resolve, reject) {
    wx.checkSession({
      success: function () {
        resolve(true);
      },
      fail: function () {
        reject(false);
      }
    })
  });
}

/**
 * 调用微信登录
 */
function login() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        if (res.code) {
          //登录远程服务器
          // console.log(res)
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}

function redirect(url) {

  //判断页面是否需要登录
  if (false) {
    wx.switchTab({
      url: '/pages/me/me'
    });
    return false;
  } else {
    wx.redirectTo({
      url: url
    });
  }
}

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    mask: true,
    image: '/static/images/icon_error.png'
  })
}

function showSuccessToast(msg) {
  wx.showToast({
    title: msg,
  })
}


function daoshu(obj){
  if (obj) {
    var date = (new Date()).valueOf();
    var now = date
    var endDate = obj.end_time;//设置截止时间
    var end = endDate
    var leftTime = end - now; //时间差 
    obj.leftTime = leftTime
    var d, h, m, s, ms;
    if (leftTime >= 0) {
      // d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
      h = Math.floor(leftTime / 1000 / 60 / 60);
      m = Math.floor(leftTime / 1000 / 60 % 60);
      s = Math.floor(leftTime / 1000 % 60);
      ms = Math.floor(leftTime % 1000);
      if (ms < 100) {
        ms = "0" + ms;
      }
      if (s < 10) {
        s = "0" + s;
      }
      if (m < 10) {
        m = "0" + m;
      }
      if (h < 10) {
        h = "0" + h;
      }

      obj.d = d
      obj.h = h
      obj.m = m
      obj.s = s
      
    } else {
      obj.d = 0
      obj.h = 0
      obj.m = 0
      obj.s = 0
      
    }
  }
}


/*获取当前页带参数的url*/
function getUrl() {
  var pages = getCurrentPages() //获取加载的页面
  var currentPage = pages[pages.length - 1] //获取当前页面的对象
  var url = currentPage.route //当前页面url
  wx.setStorageSync('Router', `/${url}`)
  var options = currentPage.options //如果要获取url中所带的参数可以查看options

  //拼接url的参数
  var urlWithArgs = url + '?'
  for (var key in options) {
    var value = options[key]
    urlWithArgs += key + '=' + value + '&'
  }
  urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
  wx.setStorageSync('Url', `/${urlWithArgs}`)
}

// 获取当前页面路由
function getRouter() {
  var pages = getCurrentPages() //获取加载的页面
  var currentPage = pages[pages.length - 1] //获取当前页面的对象
  var router = currentPage.route //当前页面url
  wx.setStorageSync('Router', `/${router}`)
}

//函数节流
function throttle(fn, timer) {
  if (timer == null || timer == undefined) {
    timer = 1000
  }

  let lastTime = null

  // 返回新的函数
  return function () {
    let nowTime = + new Date()
    if (nowTime - lastTime > timer || !lastTime) {
      fn.apply(this, arguments)   //将this和参数传给原函数
      lastTime = nowTime
    }
  }
}

module.exports = {
  getUrl,
  getRouter,
  formatTime,
  request,
  redirect,
  showErrorToast,
  showSuccessToast,
  checkSession,
  login,
  alert,
  post,
  getDistance,
  daoshu,
  throttle
}


